/** \file

\author Pablo Haramburu
Copyright: 
	Copyright (C)2010 Pablo Haramburu.
License: 
	This file is part of mundial2010.

	mundial2010 is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	mundial2010 is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with mundial2010.  If not, see <http://www.gnu.org/licenses/>.
*/

// Generated by DialogBlocks (unregistered), 31/05/2010 13:18:00

// For compilers that support precompilation, includes "wx/wx.h".
#include "wx/wxprec.h"

#ifdef __BORLANDC__
#pragma hdrstop
#endif

#ifndef WX_PRECOMP
#include "wx/wx.h"
#endif

////@begin includes
////@end includes

#include "MainDialog.h"
#include <wx/filedlg.h>
#include <wx/wupdlock.h>

////@begin XPM images
////@end XPM images


/*!
 * MainDialog type definition
 */

IMPLEMENT_DYNAMIC_CLASS( MainDialog, wxDialog )


/*!
 * MainDialog event table definition
 */

BEGIN_EVENT_TABLE( MainDialog, wxDialog )

////@begin MainDialog event table entries
    EVT_BUTTON( ID_ADD_GOALKEEPER_BUTTON, MainDialog::OnAddGoalkeeperButtonClick )

    EVT_BUTTON( ID_ADD_TESTFILE_BUTTON, MainDialog::OnAddTestfileButtonClick )

    EVT_BUTTON( ID_RUN_TESTS_BUTTON, MainDialog::OnRunTestsButtonClick )
    EVT_UPDATE_UI( ID_RUN_TESTS_BUTTON, MainDialog::OnRunTestsButtonUpdate )

////@end MainDialog event table entries

END_EVENT_TABLE()


/*!
 * MainDialog constructors
 */

MainDialog::MainDialog()
{
    Init();
}

MainDialog::MainDialog( wxWindow* parent, wxWindowID id, const wxString& caption, const wxPoint& pos, const wxSize& size, long style )
{
    Init();
    Create(parent, id, caption, pos, size, style);
}


/*!
 * MainDialog creator
 */

bool MainDialog::Create( wxWindow* parent, wxWindowID id, const wxString& caption, const wxPoint& pos, const wxSize& size, long style )
{
////@begin MainDialog creation
    SetExtraStyle(wxWS_EX_BLOCK_EVENTS);
    wxDialog::Create( parent, id, caption, pos, size, style );

    CreateControls();
    if (GetSizer())
    {
        GetSizer()->SetSizeHints(this);
    }
    Centre();
////@end MainDialog creation
    return true;
}


/*!
 * MainDialog destructor
 */

MainDialog::~MainDialog()
{
////@begin MainDialog destruction
////@end MainDialog destruction
}


/*!
 * Member initialisation
 */

void MainDialog::Init()
{
////@begin MainDialog member initialisation
    m_goalkeepers = NULL;
    m_testfiles = NULL;
////@end MainDialog member initialisation
}


/*!
 * Control creation for MainDialog
 */

void MainDialog::CreateControls()
{    
////@begin MainDialog content construction
    // Generated by DialogBlocks, 01/06/2010 04:00:41 (unregistered)

    MainDialog* itemDialog1 = this;

    wxBoxSizer* itemBoxSizer2 = new wxBoxSizer(wxVERTICAL);
    itemDialog1->SetSizer(itemBoxSizer2);

    wxBoxSizer* itemBoxSizer3 = new wxBoxSizer(wxHORIZONTAL);
    itemBoxSizer2->Add(itemBoxSizer3, 0, wxGROW, 5);

    wxStaticText* itemStaticText4 = new wxStaticText( itemDialog1, wxID_STATIC, _("Arquero(s):"), wxDefaultPosition, wxDefaultSize, 0 );
    itemBoxSizer3->Add(itemStaticText4, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5);

    itemBoxSizer3->Add(5, 5, 1, wxALIGN_CENTER_VERTICAL|wxALL, 5);

    wxButton* itemButton6 = new wxButton( itemDialog1, ID_ADD_GOALKEEPER_BUTTON, _("Agregar"), wxDefaultPosition, wxDefaultSize, 0 );
    itemBoxSizer3->Add(itemButton6, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5);

    wxArrayString m_goalkeepersStrings;
    m_goalkeepers = new wxListBox( itemDialog1, ID_GOALKEEPERS_LISTBOX, wxDefaultPosition, wxDefaultSize, m_goalkeepersStrings, wxLB_EXTENDED );
    itemBoxSizer2->Add(m_goalkeepers, 1, wxGROW|wxALL, 5);

    wxBoxSizer* itemBoxSizer8 = new wxBoxSizer(wxHORIZONTAL);
    itemBoxSizer2->Add(itemBoxSizer8, 0, wxGROW, 5);

    wxStaticText* itemStaticText9 = new wxStaticText( itemDialog1, wxID_STATIC, _("Archivos de entrada:"), wxDefaultPosition, wxDefaultSize, 0 );
    itemBoxSizer8->Add(itemStaticText9, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5);

    itemBoxSizer8->Add(5, 5, 1, wxALIGN_CENTER_VERTICAL|wxALL, 5);

    wxButton* itemButton11 = new wxButton( itemDialog1, ID_ADD_TESTFILE_BUTTON, _("Agregar"), wxDefaultPosition, wxDefaultSize, 0 );
    itemBoxSizer8->Add(itemButton11, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5);

    wxArrayString m_testfilesStrings;
    m_testfiles = new wxListBox( itemDialog1, ID_TESTSFILES_LISTBOX, wxDefaultPosition, wxDefaultSize, m_testfilesStrings, wxLB_EXTENDED );
    itemBoxSizer2->Add(m_testfiles, 0, wxGROW|wxALL, 5);

	m_showAnimation = new wxCheckBox( itemDialog1, wxID_ANY, _("Mostrar animacion") );
    itemBoxSizer2->Add(m_showAnimation, 0, wxALIGN_LEFT|wxALL, 5);

    wxBoxSizer* itemBoxSizer13 = new wxBoxSizer(wxHORIZONTAL);
    itemBoxSizer2->Add(itemBoxSizer13, 0, wxALIGN_CENTER_HORIZONTAL|wxALL, 5);

    wxButton* itemButton14 = new wxButton( itemDialog1, ID_RUN_TESTS_BUTTON, _("&Probar!"), wxDefaultPosition, wxDefaultSize, 0 );
    itemBoxSizer13->Add(itemButton14, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5);

    wxButton* itemButton15 = new wxButton( itemDialog1, wxID_CANCEL, _("&Cancel"), wxDefaultPosition, wxDefaultSize, 0 );
    itemBoxSizer13->Add(itemButton15, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5);

    // Connect events and objects
    m_goalkeepers->Connect(ID_GOALKEEPERS_LISTBOX, wxEVT_KEY_DOWN, wxKeyEventHandler(MainDialog::OnGoalkeepersListboxKeyDown), NULL, this);
    m_testfiles->Connect(ID_TESTSFILES_LISTBOX, wxEVT_KEY_DOWN, wxKeyEventHandler(MainDialog::OnTestsfilesListboxKeyDown), NULL, this);
////@end MainDialog content construction


	m_showAnimation->SetValue(true);

	//inicializamos el contenido de las listas
	{
		wxArrayString paths;
		m_model.getGoalkeepers(paths);
		m_goalkeepers->Append(paths);
	}
	{
		wxArrayString paths;
		m_model.getTestfiles(paths);
		m_testfiles->Append(paths);
	}

}


/*!
 * Should we show tooltips?
 */

bool MainDialog::ShowToolTips()
{
    return true;
}

/*!
 * Get bitmap resources
 */

wxBitmap MainDialog::GetBitmapResource( const wxString& name )
{
    // Bitmap retrieval
////@begin MainDialog bitmap retrieval
    wxUnusedVar(name);
    return wxNullBitmap;
////@end MainDialog bitmap retrieval
}

/*!
 * Get icon resources
 */

wxIcon MainDialog::GetIconResource( const wxString& name )
{
    // Icon retrieval
////@begin MainDialog icon retrieval
    wxUnusedVar(name);
    return wxNullIcon;
////@end MainDialog icon retrieval
}


/*!
 * wxEVT_COMMAND_BUTTON_CLICKED event handler for ID_ADD_GOALKEEPER_BUTTON
 */

void MainDialog::OnAddGoalkeeperButtonClick( wxCommandEvent& event )
{
	wxFileDialog dlg(this, _("Seleccione archivos de arqueros"),
		wxT(""), wxT(""), _("Ejecutables (*.exe)|*.exe|Todos los archivos (*.*)|*.*"), 
		wxFD_OPEN | wxFD_FILE_MUST_EXIST | wxFD_MULTIPLE | wxFD_CHANGE_DIR);
	if (dlg.ShowModal() == wxID_OK)
	{
		wxArrayString paths;
		dlg.GetPaths(paths);
		m_model.addGoalkeepers(paths);
		m_model.getGoalkeepers(paths);

		wxWindowUpdateLocker lock(this);
		m_goalkeepers->Clear();
		m_goalkeepers->Append(paths);
	}
}


/*!
 * wxEVT_COMMAND_BUTTON_CLICKED event handler for ID_ADD_TESTFILE_BUTTON
 */

void MainDialog::OnAddTestfileButtonClick( wxCommandEvent& event )
{
	wxFileDialog dlg(this, _("Seleccione archivos de prueba"),
		wxT(""), wxT(""), _("Todos los archivos (*.*)|*.*"), 
		wxFD_OPEN | wxFD_FILE_MUST_EXIST | wxFD_MULTIPLE | wxFD_CHANGE_DIR);
	if (dlg.ShowModal() == wxID_OK)
	{
		wxArrayString paths;
		dlg.GetPaths(paths);
		m_model.addTestfiles(paths);
		m_model.getTestfiles(paths);

		wxWindowUpdateLocker lock(this);
		m_testfiles->Clear();
		m_testfiles->Append(paths);
	}
}

class TooSimpleGUI : public ITestGUI
{
public:
	TooSimpleGUI(wxWindow * parent) : m_parent(parent) {}
public: /// \name ITestGUI
	virtual void testingStarts() {}
	virtual void testingEnded() {}
	virtual void setGoalkeeperName(const wxString & name) { m_goalkeeper = name; }
	virtual void setTestName(const wxString & name) { m_testfile = name; }
	virtual void goalkeeperStarts() {}
	virtual void goalkeeperEnded() {}
	virtual void reportTestFailure(const wxString & message)
	{
		wxString s;
		s += _("Arquero: ") + m_goalkeeper + wxT("\n");
		s += _("Test: ") + m_testfile + wxT("\n");
		s += message;
		wxMessageBox(s, _("Fallo el test"), wxOK, m_parent);
	}
	virtual void reportSimulation(bool isGoal, const std::vector<SimulationStep> & simulation)
	{
		wxString s;
		s += _("Arquero: ") + m_goalkeeper + wxT("\n");
		s += _("Test: ") + m_testfile + wxT("\n");
		s += isGoal ? _("Goool !!") : _("El arqueeero !!");
		wxMessageBox(s, _("Resultado"), wxOK, m_parent);
	}
private:
	wxWindow * m_parent;
	wxString m_goalkeeper;
	wxString m_testfile;
};

#include "TestResultsDialog.h"

class SimpleGUI : public ITestGUI
{
public:
	SimpleGUI(wxWindow * parent) : m_dlg(parent), m_catched(0), m_total(0) {}
public: /// \name ITestGUI
	virtual void testingStarts() { m_dlg.m_cancelBtn->Disable(); m_dlg.Show(); }
	virtual void testingEnded() { m_dlg.Hide(); m_dlg.m_cancelBtn->Enable(); m_dlg.ShowModal(); }
	virtual void setGoalkeeperName(const wxString & name) 
	{ 
		m_goalkeeper = name; 
		m_catched = 0;
		m_total = 0;
		long item = m_dlg.m_summary->InsertItem(m_dlg.m_summary->GetItemCount(), m_goalkeeper);
		m_dlg.m_summary->SetItem(item, 1, wxString() << m_catched);
		m_dlg.m_summary->SetItem(item, 2, wxString() << m_total);
	}
	virtual void setTestName(const wxString & name) { m_testfile = name; }
	virtual void goalkeeperStarts() {}
	virtual void goalkeeperEnded() {}
	virtual void reportTestFailure(const wxString & message)
	{
		wxString s;
		s += _("Arquero: ") + m_goalkeeper + wxT("\n");
		s += _("Test: ") + m_testfile + wxT("\n");
		s += message;
		wxMessageBox(s, _("Fallo el test"), wxOK, &m_dlg);
	}
	virtual void reportSimulation(bool isGoal, const std::vector<SimulationStep> & simulation)
	{
		long item = m_dlg.m_results->InsertItem(m_dlg.m_results->GetItemCount(), m_goalkeeper);
		m_dlg.m_results->SetItem(item, 1, m_testfile);
		m_dlg.m_results->SetItem(item, 2, isGoal ? _("Goool !!") : _("El arqueeero !!"));
		if (!isGoal) ++m_catched;
		++m_total;
		item = m_dlg.m_summary->GetItemCount()-1; //zero-based
		m_dlg.m_summary->SetItem(item, 1, wxString() << m_catched);
		m_dlg.m_summary->SetItem(item, 2, wxString() << m_total);
	}
private:
	TestResultsDialog m_dlg;
	wxString m_goalkeeper;
	wxString m_testfile;
	size_t m_catched;
	size_t m_total;
};

#include "ShotAnimationDialog.h"

class AnimationGUI : public ITestGUI
{
public:
	AnimationGUI(wxWindow * parent) : m_dlg(parent), m_catched(0), m_total(0), m_cancelled(false) {}
public: /// \name ITestGUI
	virtual void testingStarts() { m_dlg.Show(); }
	virtual void testingEnded() { m_dlg.Hide(); if (!m_cancelled) m_dlg.ShowModal(); }
	virtual void setGoalkeeperName(const wxString & name) 
	{ 
		m_goalkeeper = name; 
		m_catched = 0;
		m_total = 0;
		m_dlg.m_goalkeeper->SetValue(m_goalkeeper);
	}
	virtual void setTestName(const wxString & name) 
	{ 
		m_testfile = name;
		m_dlg.m_testfile->SetValue(m_testfile);
	}
	virtual void goalkeeperStarts() {}
	virtual void goalkeeperEnded() {}
	virtual void reportTestFailure(const wxString & message)
	{
		wxString s;
		s += _("Arquero: ") + m_goalkeeper + wxT("\n");
		s += _("Test: ") + m_testfile + wxT("\n");
		s += message;
		wxMessageBox(s, _("Fallo el test"), wxOK, &m_dlg);
	}
	virtual void reportSimulation(bool isGoal, const std::vector<SimulationStep> & simulation)
	{
		if (!isGoal) ++m_catched;
		++m_total;
		m_dlg.m_goalkeeper->SetValue(m_goalkeeper);
		m_dlg.m_testfile->SetValue(m_testfile);
		m_dlg.setSimulation(simulation);
		if (!m_cancelled) {
			m_dlg.Hide(); 
			m_cancelled = wxID_CANCEL == m_dlg.ShowModal(); 
			m_dlg.Show();
		}
	}
private:
	ShotAnimationDialog m_dlg;
	wxString m_goalkeeper;
	wxString m_testfile;
	size_t m_catched;
	size_t m_total;
	bool m_cancelled;
};


/*!
 * wxEVT_COMMAND_BUTTON_CLICKED event handler for ID_RUN_TESTS_BUTTON
 */

void MainDialog::OnRunTestsButtonClick( wxCommandEvent& event )
{
	//TooSimpleGUI gui(this);
	if (m_showAnimation->IsChecked()) {
		AnimationGUI gui(this);
		m_model.runTests(gui);
	} else {
		SimpleGUI gui(this);
		m_model.runTests(gui);
	}
}


/*!
 * wxEVT_UPDATE_UI event handler for ID_RUN_TESTS_BUTTON
 */

void MainDialog::OnRunTestsButtonUpdate( wxUpdateUIEvent& event )
{
	event.Enable(m_model.canRunTests());
}

void collectSelection(wxListBox * lst, wxArrayString & items)
{
	wxArrayInt selection;
	int nSelect = lst->GetSelections(selection);
	if (nSelect <= 0 || nSelect != selection.size())
		return;
	items.clear();
	items.reserve(nSelect);
	for (size_t i = 0; i < nSelect; ++i) {
		wxString s = lst->GetString(selection[i]);
		assert(!s.empty());
		if (!s.empty())
			items.push_back(s);
	}
}





/*!
 * wxEVT_KEY_DOWN event handler for ID_GOALKEEPERS_LISTBOX
 */

void MainDialog::OnGoalkeepersListboxKeyDown( wxKeyEvent& event )
{
	if (event.GetKeyCode() == WXK_DELETE) //untranslated non-unicode...
	{
		wxArrayString paths;
		collectSelection(m_goalkeepers, paths);
		if (!paths.empty()) {
			m_model.deleteGoalkeepers(paths);
			m_model.getGoalkeepers(paths);

			wxWindowUpdateLocker lock(this);
			m_goalkeepers->Clear();
			m_goalkeepers->Append(paths);
			return;
		}
	}

	event.Skip();
}


/*!
 * wxEVT_KEY_DOWN event handler for ID_TESTSFILES_LISTBOX
 */

void MainDialog::OnTestsfilesListboxKeyDown( wxKeyEvent& event )
{
	if (event.GetKeyCode() == WXK_DELETE) //untranslated non-unicode...
	{
		wxArrayString paths;
		collectSelection(m_testfiles, paths);
		if (!paths.empty()) {
			m_model.deleteTestfiles(paths);
			m_model.getTestfiles(paths);

			wxWindowUpdateLocker lock(this);
			m_testfiles->Clear();
			m_testfiles->Append(paths);
			return;
		}
	}

	event.Skip();
}

